﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO;
using System.Drawing;
using System.Web.UI;
using Quartz;
using Quartz.Impl;
using System.Threading.Tasks;
using AiXiu.BLL;
using AiXiu.IBLL;
using AiXiu.Model;
using AiXiu.Common;

namespace AiXiu.WebSite
{
    public class Global : System.Web.HttpApplication
    {
        protected async void Application_Start(object sender, EventArgs e)
        {
            //设置日志文件存储位置
            FileInfo fileinfo = new FileInfo(Server.MapPath("~/log4net.config"));
            log4net.Config.XmlConfigurator.Configure(fileinfo);



            #region 任务调度器 同步视频状态和封面

            // 从工厂中获取一个调度器实例化
            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();
            //开启调度器
            await scheduler.Start();
            //创建一个作业
            IJobDetail job = JobBuilder.Create<SyncVideosJob>()
                .WithIdentity("SyncVideosJob", "Video")
                .Build();
            //创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("SyncVideosTrigger", "Video")
                .StartNow()//从现在开始执行
                .WithSimpleSchedule(m => m
                    .WithIntervalInSeconds(10)//每隔几秒执行
                    .RepeatForever())//永远重复执行
                .Build();
            await scheduler.ScheduleJob(job, trigger);

            #endregion
        }
    }

    internal class SyncVideosJob : IJob
    {
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Run(() =>
            {
                //调用BLL层同步视频的方法
                IVideoBLL videoBLL = new VideoBLL();
                int updateCount = videoBLL.UpdateVideoState();
                //如果更新数量>0,日志记录数量和时间 
                if (updateCount > 0)
                {
                    LogHelper.Info(string.Format("更新视频状态条数: {0}, 更新时间: {1};", updateCount, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                }
            });
        }
    }
}